import 'dart:async';

// import 'package:euromillions/tools/EJ_config.dart';
import 'package:bordered_text/bordered_text.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../tools/FL_CustomLoading.dart';
import '../../tools/KaL_Config.dart';
import '../../tools/models/KL_keralaLottoDataModel.dart';
import '../../tools/models/KL_keralaLottoModel.dart';
import '../../tools/models/KaL_LottoModel.dart';

class EJHeaderView_HomePage extends StatefulWidget {
  EJHeaderView_HomePage({super.key, required this.model, this.nextDrawnModel});
  final KaL_LottoModel model;
  NextDrawModel? nextDrawnModel;
  @override
  State<EJHeaderView_HomePage> createState() => _EJHeaderView_HomePageState();
}

class _EJHeaderView_HomePageState extends State<EJHeaderView_HomePage> {
  ///下一期数据模型
  late var _nextDrawnModel = NextDrawModel();

  late var _nextDrawDateTime = '';
  late var _nextjackpot = '';
  late var _timeDiffToNextDraw = 0;

  int _hours = 0;
  int _minutes = 0;
  int _seconds = 0;

  ///倒计时定时器
  late Timer _timer;

  _EJ_countDownTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() {
        if (_timeDiffToNextDraw < 1) {
          _timer.cancel();
          Future.delayed(const Duration(seconds: 3), () {
            getNextDrawnData();
          });
        } else {
          _timeDiffToNextDraw--;
        }
      });
    });
  }

  void formatTime(int seconds) {
    int hours = (_timeDiffToNextDraw ~/ 3600);
    int minutes = (_timeDiffToNextDraw % 3600) ~/ 60;
    int seconds = _timeDiffToNextDraw % 60;

    _hours = int.parse(hours.toString().padLeft(2, '0'));
    _minutes = int.parse(minutes.toString().padLeft(2, '0'));
    _seconds = int.parse(seconds.toString().padLeft(2, '0'));

    // return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  void buyTicketButtonClick() async {
    debugPrint('BUY TICKETS');
    String configLink = _nextDrawnModel.link!;
    Uri _url = Uri.parse(configLink);
    if (configLink.isNotEmpty) {
      if (!await launchUrl(_url, mode: LaunchMode.externalApplication)) {
        throw Exception('Could not launch $_url');
      }
    }
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _nextDrawnModel = widget.nextDrawnModel!;
    _configNextDrawnTimer(_nextDrawnModel);
    getNextDrawnData();
  }

  //
  void _configNextDrawnTimer(NextDrawModel nextDrawnmodel) {
    var gameName = nextDrawnmodel.game_name;
    var gameCode = nextDrawnmodel.draw_code;
    _nextjackpot = '$gameName \n($gameCode)';

    var draw_datetime_utc = _nextDrawnModel.draw_datetime_utc;
    DateTime nextDateTime =
        DateTime.parse(draw_datetime_utc + '+0000').toLocal();

    ///
    _nextDrawDateTime = DateFormat('EEE, MMM d, y').format(nextDateTime);

    // 获取next时间戳（以毫秒为单位）
    int nextTimestamp = (nextDateTime.millisecondsSinceEpoch / 1000).round();

    // 获取当前时间
    DateTime now = DateTime.now();
    // 获取当前时间戳（以毫秒为单位）
    int timestampInMilliseconds = (now.millisecondsSinceEpoch / 1000).round();

    _timeDiffToNextDraw = nextTimestamp - timestampInMilliseconds;

    _EJ_countDownTimer();
  }

  ///
  void getNextDrawnData() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        themeColor: KaL_Config.KaL_themeColor_HL,
      );
    });

    bool isGet = await KL_keralaLottoDataModel().getNextDrawnData();
    if (isGet) {
      _timer.cancel();
      BotToast.closeAllLoading();
      _nextDrawnModel = KL_keralaLottoDataModel().nextDrawnModel;
      _configNextDrawnTimer(_nextDrawnModel);
    }
  }

  @override
  Widget build(BuildContext context) {
    //时间戳转时分秒
    formatTime(_timeDiffToNextDraw);

    var secondStr = _seconds < 10 ? '0$_seconds' : _seconds.toString();
    var minutesStr = _minutes < 10 ? '0$_minutes' : _minutes.toString();
    var hourStr = _hours < 10 ? '0$_hours' : _hours.toString();

    return Container(
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(10),
      // height: 200,
      // color: Colors.yellow,
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色
            spreadRadius: 1, // 扩散半径
            blurRadius: 10, // 模糊半径
            offset: const Offset(0, 1), // 阴影偏移
          ),
        ],
        borderRadius: const BorderRadius.all(Radius.circular(10)),
        gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              KaL_Config.KaL_themeColor_HL,
              KaL_Config.KaL_themeColor_N
            ]),
      ),
      child: Column(
        children: [
          Container(
            height: 25,
            padding: const EdgeInsets.fromLTRB(25, 3, 25, 3),
            decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.3),
                borderRadius:
                    const BorderRadius.all(Radius.circular(25 * 0.5))),
            child: const Text(
              'NEXT DRAW',
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 12,
                  fontWeight: FontWeight.w500),
            ),
          ),
          const SizedBox(height: 5),
          BorderedText(
            strokeWidth: 5.0,
            strokeColor: KaL_Config.KaL_jackpottextColor_w,
            child: Text(
              _nextjackpot,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: HexColor('#d32f7d'),
                fontSize: 28.0,
                fontWeight: FontWeight.w900,
              ),
            ),
          ),
          Text(
            _nextDrawDateTime,
            style: TextStyle(
              height: 3,
              fontWeight: FontWeight.w900,
              fontSize: 16,
              color: KaL_Config.KaL_MainColor,
            ),
          ),
          const SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              timeView('HOURS', hourStr),
              const SizedBox(width: 10),
              timeView('MINUTES', minutesStr),
              const SizedBox(width: 10),
              timeView('SECONDS', secondStr),
            ],
          ),
          const SizedBox(height: 15),
          playableButton(),
        ],
      ),
    );
  }

  Widget timeView(String typeStr, String timeStr) {
    return Column(
      children: [
        Container(
          alignment: Alignment.center,
          height: 50,
          width: 60,
          decoration: const BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Text(
            timeStr,
            style: const TextStyle(
                fontWeight: FontWeight.w800, fontSize: 34, color: Colors.white),
          ),
        ),
        Text(
          typeStr,
          style: const TextStyle(color: Colors.black, fontSize: 14),
        ),
      ],
    );
  }

  //play按钮
  Widget playableButton() {
    return Container(
      height: 45,
      width: 150,
      decoration: BoxDecoration(
        color: HexColor('#d32f7d'),
        borderRadius: const BorderRadius.all(Radius.circular(25)),
      ),
      child: OutlinedButton(
        onPressed: () {
          buyTicketButtonClick();
        },
        style: ButtonStyle(
          side: WidgetStateProperty.all(
              BorderSide(width: 2.0, color: Colors.white)),
        ),
        child: Text(
          // 'buy ticket',
          _nextDrawnModel.playable_text!,
          textAlign: TextAlign.center,
          style: TextStyle(
              height: 1.1, //行间距
              fontSize: 15.0,
              color: Colors.white,
              fontWeight: FontWeight.w600),
        ),
      ),
    );
  }
}
